//
// Created by LoveHoneyYou on 2024-11-17.
//

#include "ThreadPool.h"
ThreadPool::ThreadPool(EventLoop *mainloop, int count)
                :index_(0)
                ,is_start_(false)
                ,main_loop_(mainloop)
                ,thread_num_(count)
{}

ThreadPool::~ThreadPool()
{
    for(auto item : worker_threads_)
    {
        delete item;
    }
}

void ThreadPool::Run()
{
    if(!is_start_)
    {
        if(main_loop_->Get_Thread_Id() != std::this_thread::get_id())
        {
            exit(0);
        }
        is_start_ = true;
        if(thread_num_ > 0)
        {
            for(int i = 0; i < thread_num_; ++i)
            {
                WorkerThread* sub_thread = new WorkerThread(i);
                sub_thread->Run();
                worker_threads_.push_back(sub_thread);
            }
        }
    }
}

EventLoop *ThreadPool::Task_Worker_Event_Loop()
{
    if(is_start_)
    {
        if(main_loop_->Get_Thread_Id() != std::this_thread::get_id())
        {
            exit(0);
        }
        EventLoop* eventloop = main_loop_;
        if(thread_num_ > 0)
        {
            eventloop = worker_threads_[index_]->GetEventLoop();
            index_ = ++index_ % thread_num_;
        }
        return eventloop;
    }
    return nullptr;
}
